export function toDateObject(timeStr) {
  if (typeof (timeStr) === 'string' && !isNaN(Date.parse(timeStr))) {
    return new Date(timeStr.replace(new RegExp('-', 'g'), '/'))
  } else {
    return new Date()
  }
}

export function toDateString(targetDate, foramtStr = '%Y-%m-%d %H:%M:%S') {
  let t = Object.prototype.toString.call(targetDate) === '[object Date]' ? targetDate : new Date()
  let y = t.getFullYear(), m = t.getMonth() + 1, d = t.getDate()
  let s = `${y}-${m < 10 ? '0' + m : m}-${d < 10 ? '0' + d : d}`
  let l = 8 - (17 - foramtStr.length)
  return l > 0 ? `${s} ${t.toTimeString().substr(0, l)}` : s
}

export function formatPrice(price) {
  let value = String(price).indexOf('.') != -1 ? price.toFixed(2) : String(price)
  return value.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}

export function numberFormat(value, digit = 0) {
  if (typeof value === 'number') {
    let v = 0,
      k = 10000,
      f = ['', '万', '亿', '万亿'],
      i = 0
    if (value > k) {
      i = Math.floor(Math.log(value) / Math.log(k))
      v = (value / Math.pow(k, i)).toFixed(digit)
    } else {
      v = value.toFixed(digit)
    }
    return `${v}${f[i]}`
  } else {
    return 0
  }

}

export function getOptionsTarget(array, field, value, target) {
  for (let i = 0; i < array.length; i++) {
    if (array[i][field] === value) {
      return array[i][target]
    }
  }
}

export function getColor(value) {
  if (value > 0) {
    return '#F56C6C'
  } else if (value < 0) {
    return '#67C23A'
  } else {
    return '#2c3e50'
  }
}

export function deepClone(obj) {
  return JSON.parse(JSON.stringify(obj));
}

export function deepMerge(source, target) {
  let targetObject = deepClone(target);
  for (const key in source) {
    if (Object.prototype.hasOwnProperty.call(source, key)) {
      const sourceValue = source[key];
      const targetValue = targetObject[key];
      if (typeof sourceValue === 'object' && typeof targetValue === 'object') {
        targetObject[key] = deepMerge(sourceValue, targetValue);
      } else {
        targetObject[key] = sourceValue;
      }
    }
  }
  return targetObject;
}
